package zust.javaee.service.Impl;

import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zust.javaee.dao.hibernate.BaseDao;
import zust.javaee.dto.AjaxReturn;
import zust.javaee.dto.SessionInfo;
import zust.javaee.dto.admin.*;
import zust.javaee.dto.adminadd.CorporationAddDto;
import zust.javaee.dto.adminadd.PlayerAddDto;
import zust.javaee.entity.*;
import zust.javaee.enums.Corporation.CorporationStatusEnum;
import zust.javaee.enums.Corporation.CorporationTypeEnum;
import zust.javaee.enums.Member.MemberLevelEnum;
import zust.javaee.enums.Member.MemberStatusEnum;
import zust.javaee.enums.player.PlayerStatusEnum;
import zust.javaee.enums.player.PlayerTypeEnum;
import zust.javaee.service.AdminServive;
import zust.javaee.util.MD5Util;
import zust.javaee.util.StrUtil;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by liy on 2017/1/8.
 */

@Service
@Transactional
public class AdminServiceImpl extends BaseServiceImpl<Tplayer> implements AdminServive {

    @Autowired
    private BaseDao<Tplayer> playerDao;


    @Autowired
    private BaseDao<Tcorporation> corporationDao;


    @Autowired
    private BaseDao<Tactivity> activityDao;

    @Autowired
    private BaseDao<Tannouncement> announcementDao;

    @Autowired
    private BaseDao<Tmember> memberDao;


    @Autowired
    private BaseDao<TrequisitionForm> reqFormDao;


    @Autowired
    private BaseDao<TsignupCorporation> signCorporDao;

    @Autowired
    private BaseDao<TsignupActivityForm> signActivityDao;

    SimpleDateFormat sdfE = new SimpleDateFormat("dd-MM-yyyy");

    @Override
    public AjaxReturn<SessionInfo> doLogin(String sId, String password, HttpSession session) {
        if (countPlayerByStudentId(sId) < 1) {
            return new AjaxReturn<>(false, "用户名输入错误");
        } else {
            /**  main  */
            try {
                Tplayer tplayer = getPlayerByStudentId(sId);
                if (tplayer.getPassword().equals(password) || MD5Util.validPassword(password, tplayer.getPassword())) {
                    if (tplayer.getType() == PlayerTypeEnum.SUPER.getType()) {
                        //成功通过验证
                        SessionInfo sessionInfo = new SessionInfo(tplayer);
                        session.setAttribute("sessionInfo", sessionInfo);
                        return new AjaxReturn<>(true, "登陆成功", sessionInfo);
                    } else {
                        return new AjaxReturn<>(false, "权限不够");
                    }
                } else {
                    return new AjaxReturn<>(false, "密码错误");
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                return new AjaxReturn<>(false, "Exception");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return new AjaxReturn<>(false, "Exception");
            }
        }
    }

    @Override
    public void addPlayer(PlayerAddDto playerAddDto){
        Tplayer tplayer = new Tplayer();
        BeanUtils.copyProperties(playerAddDto, tplayer);
        try {
            tplayer.setPassword(MD5Util.getEncryptedPwd("123456"));
            tplayer.setCorporationNum(0);
            tplayer.setBirth(sdfE.parse(playerAddDto.getBirthStr()));
            tplayer.setStatus(PlayerStatusEnum.AVAILABLE.getStatus());
            tplayer.setType(PlayerTypeEnum.REGISTER.getType());
            playerDao.save(tplayer);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updatePlayer(Integer playerId, PlayerAddDto playerAddDto) {
        Tplayer tplayer = playerDao.get(Tplayer.class, playerId);
        BeanUtils.copyProperties(playerAddDto, tplayer);
        try {
            tplayer.setBirth(sdfE.parse(playerAddDto.getBirthStr()));
            playerDao.update(tplayer);
        }catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateCorporation(Integer corporId, CorporationAddDto corporationAddDto) {
        Tcorporation tcorporation = corporationDao.get(Tcorporation.class, corporId);
        BeanUtils.copyProperties(corporationAddDto, tcorporation);
        corporationDao.update(tcorporation);
    }

    @Override
    public boolean changePlayerStatu(Integer playerId, Short statu) {
        Tplayer tplayer = playerDao.get(Tplayer.class, playerId);
        if (tplayer == null)
            return false;
        else {
            tplayer.setStatus(statu);
            playerDao.update(tplayer);
            return true;
        }
    }

    @Override
    public boolean changeSigncorporStatu(Integer id, Short statu) {
        TsignupCorporation tsignCorpor = signCorporDao.get(TsignupCorporation.class, id);
        if (tsignCorpor == null)
            return false;
        else {
            tsignCorpor.setStatus(statu);
            signCorporDao.update(tsignCorpor);
            return true;
        }
    }

    @Override
    public boolean changeCorporationStatu(Integer id, Short statu) {
        Tcorporation tcorporation = corporationDao.get(Tcorporation.class, id);
        if (tcorporation == null)
            return false;
        else {
            tcorporation.setStatus(statu);
            corporationDao.update(tcorporation);
            return true;
        }
    }

    @Override
    public boolean changeActivityStatu(Integer id, Short statu) {
        Tactivity tactivity = activityDao.get(Tactivity.class, id);
        if (tactivity == null)
            return false;
        else {
            tactivity.setStatus(statu);
            activityDao.update(tactivity);
            return true;
        }
    }

    @Override
    public boolean changeAnnouncementStatu(Integer id, Short statu) {
        Tannouncement tannouncement = announcementDao.get(Tannouncement.class, id);
        if (tannouncement == null)
            return false;
        else {
            tannouncement.setType(statu);
            announcementDao.update(tannouncement);
            return true;
        }
    }

    @Override
    public boolean passSignCorpor(Integer signCorporId) {
        TsignupCorporation tsignCorpor = signCorporDao.get(TsignupCorporation.class, signCorporId);
        Tplayer tp = playerDao.get(Tplayer.class, tsignCorpor.getTplayer().getId());
        Tcorporation tcorporation = new Tcorporation();


        BeanUtils.copyProperties(tsignCorpor, tcorporation);
        tcorporation.setStatus((short) 1);
        corporationDao.save(tcorporation);

        //自己就是成员
        Tcorporation newcorpor = getCloseTimeCorporation();
        Tmember tmember = new Tmember();
        tmember.setTcorporation(newcorpor);
        tmember.setTplayer(tp);
        tmember.setLevel(MemberLevelEnum.STAR5.getStatus());
        tmember.setJoinTime(new Date());
        tmember.setPosition("社长");
        tmember.setStatus(MemberStatusEnum.AVAILABLE.getStatus());
        memberDao.save(tmember);
        return true;
    }

    @Override
    public Long getPlayerNum() {
        String hql = "select count(*) from Tplayer";
        return playerDao.count(hql);
    }

    @Override
    public Long getCorporationNum() {
        String hql = "select count(*) from Tcorporation";
        return corporationDao.count(hql);
    }

    @Override
    public List<PlayerListDto> getPlayerIndexList(Short status, Integer page, Integer rows, String keywd, String sort) {
        String hql = " from Tplayer p where p.status =" + status;

        // 搜索
        if (!StrUtil.hasEmpty(keywd)) {
            String key = "'%" + keywd + "%'";
            hql += " and ( p.studentId like " + key;
            hql += " or p.name like " + key;
            // hql += " or cast(d.sfzNo as string) like " + key;
            hql += " ) ";
        }

        // 排序
        String sortHql = " order by p.id desc";
        if (!StrUtil.hasEmpty(sort)) {
            sortHql = " order by p." + sort;
        }
        hql += sortHql;

        List<Tplayer> tplayers = playerDao.find(hql, page, rows);
        List<PlayerListDto> playerListDtos = new ArrayList<>();
        for (Tplayer tplayer : tplayers) {
            String gen = "";
            if (tplayer.getGender() != null)
                gen = tplayer.getGender() == 0 ? "女" : "男";
            PlayerListDto playerListDto = new PlayerListDto();
            BeanUtils.copyProperties(tplayer, playerListDto);
            playerListDto.setGender(gen);
            playerListDto.setType(PlayerTypeEnum.stateOf(tplayer.getType()));
            playerListDtos.add(playerListDto);
        }
        return playerListDtos;
    }

    @Override
    public long getPlayerPageNum(short status, Integer page, Integer rows, String keywd, String sort) {
        String hql = "select count(*) from Tplayer p where p.status =" + status;

        // 搜索
        if (!StrUtil.hasEmpty(keywd)) {
            String key = "'%" + keywd + "%'";
            hql += " and ( p.studentId like " + key;
            hql += " or p.name like " + key;
            // hql += " or cast(d.sfzNo as string) like " + key;
            hql += " ) ";
        }


        long size = playerDao.count(hql);
        long pageNum = size / rows + (size % rows == 0 ? 0 : 1);
        return pageNum;
    }

    @Override
    public long getPlayerNum(short status, String keywd) {
        String hql = "select count(*) from Tplayer p where p.status =" + status;

        // 搜索
        if (!StrUtil.hasEmpty(keywd)) {
            String key = "'%" + keywd + "%'";
            hql += " and ( p.studentId like " + key;
            hql += " or p.name like " + key;
            // hql += " or cast(d.sfzNo as string) like " + key;
            hql += " ) ";
        }

        return playerDao.count(hql);
    }

    @Override
    public List<PlayerListDto> getPlayerIndexList(Short status) {
        String hql = " from Tplayer p where p.status =" + status;
        List<Tplayer> tplayers = playerDao.find(hql);
        List<PlayerListDto> playerListDtos = new ArrayList<>();
        for (Tplayer tplayer : tplayers) {
            String gen = "";
            if (tplayer.getGender() != null)
                gen = tplayer.getGender() == 0 ? "女" : "男";
            PlayerListDto playerListDto = new PlayerListDto();
            BeanUtils.copyProperties(tplayer, playerListDto);
            playerListDto.setGender(gen);
            playerListDto.setType(PlayerTypeEnum.stateOf(tplayer.getType()));
            playerListDtos.add(playerListDto);
        }
        return playerListDtos;
    }

    @Override
    public List<PlayerListDto> getPlayerIndexListExcept(Short status) {
        String hql = " from Tplayer p where p.status !=" + status;
        List<Tplayer> tplayers = playerDao.find(hql);
        List<PlayerListDto> playerListDtos = new ArrayList<>();
        for (Tplayer tplayer : tplayers) {
            PlayerListDto playerListDto = new PlayerListDto();
            String gen = "";
            if (tplayer.getGender() != null)
                gen = tplayer.getGender() == 0 ? "女" : "男";
            BeanUtils.copyProperties(tplayer, playerListDto);
            playerListDto.setGender(gen);
            playerListDto.setType(PlayerTypeEnum.stateOf(tplayer.getType()));
            playerListDto.setStatu(PlayerStatusEnum.stateOf(tplayer.getStatus()));
            playerListDtos.add(playerListDto);
        }
        return playerListDtos;
    }

    @Override
    public List<CorporListDto> getCorporIndexList(Short status) {
        String hql = " from Tcorporation l where l.status = " + status + " order by l.id";
        List<Tcorporation> tcorporations = corporationDao.find(hql);
        List<CorporListDto> corporListDtos = new ArrayList<>();
        for (Tcorporation tcorporation : tcorporations) {
            CorporListDto corporListDto = new CorporListDto();
            BeanUtils.copyProperties(tcorporation, corporListDto);
            if (tcorporation.getType() != null)
                corporListDto.setTypes(CorporationTypeEnum.stateOf(tcorporation.getType()));
            if (tcorporation.getTplayer() != null) {
                Tplayer tplayer = playerDao.get(Tplayer.class, tcorporation.getTplayer().getId());
                corporListDto.setPlayerName(tplayer.getName());
                corporListDto.setPlayerId(tplayer.getId());
            }
            corporListDtos.add(corporListDto);
        }
        return corporListDtos;
    }

    @Override
    public List<CorporListDto> getCorporIndexListExcept(Short status) {
        String hql = " from Tcorporation l where l.status != " + status + " order by l.id";
        List<Tcorporation> tcorporations = corporationDao.find(hql);
        List<CorporListDto> corporListDtos = new ArrayList<>();
        for (Tcorporation tcorporation : tcorporations) {
            CorporListDto corporListDto = new CorporListDto();
            BeanUtils.copyProperties(tcorporation, corporListDto);
            if (tcorporation.getTplayer() != null) {
                Tplayer tplayer = playerDao.get(Tplayer.class, tcorporation.getTplayer().getId());
                corporListDto.setPlayerId(tplayer.getId());
                corporListDto.setPlayerName(tplayer.getName());
            }
            if (tcorporation.getType() != null)
                corporListDto.setTypes(CorporationTypeEnum.stateOf(tcorporation.getType()));
            corporListDto.setStatu(CorporationStatusEnum.stateOf(tcorporation.getStatus()));
            corporListDtos.add(corporListDto);
        }
        return corporListDtos;
    }

    @Override
    public List<ActivityListDto> getActivityIndexList(Short status) {
        String hql = " from Tactivity l where l.status = " + status;
        List<Tactivity> tactivities = activityDao.find(hql);
        List<ActivityListDto> activityListDtos = new ArrayList<>();
        for (Tactivity tactivity : tactivities) {
            ActivityListDto activityListDto = new ActivityListDto();
            BeanUtils.copyProperties(tactivity, activityListDto);
            Tcorporation tcor = corporationDao.get(Tcorporation.class,
                    tactivity.getTcorporation().getId());
            activityListDto.setCorporarionName(tcor.getName());
            activityListDto.setCorporarionId(tcor.getId());
            Tmember tmember = memberDao.get(Tmember.class,
                    tactivity.getPrincipal().getId());
            Tplayer tplayer = playerDao.get(Tplayer.class, tmember.getTplayer().getId());
            activityListDto.setPrincipalId(tmember.getId());
            activityListDto.setPrincipalName(tplayer.getName());
            activityListDtos.add(activityListDto);
        }
        return activityListDtos;
    }

    @Override
    public List<ActivityListDto> getActivityIndexListLess(Short status) {
        String hql = " from Tactivity l where l.status <= " + status;
        List<Tactivity> tactivities = activityDao.find(hql);
        List<ActivityListDto> activityListDtos = new ArrayList<>();
        for (Tactivity tactivity : tactivities) {
            ActivityListDto activityListDto = new ActivityListDto();
            BeanUtils.copyProperties(tactivity, activityListDto);
            Tcorporation tcor = corporationDao.get(Tcorporation.class,
                    tactivity.getTcorporation().getId());
            activityListDto.setCorporarionId(tcor.getId());
            activityListDto.setCorporarionName(tcor.getName());
            Tmember tmember = memberDao.get(Tmember.class,
                    tactivity.getPrincipal().getId());
            Tplayer tplayer = playerDao.get(Tplayer.class, tmember.getTplayer().getId());
            activityListDto.setPrincipalName(tplayer.getName());
            activityListDto.setPrincipalId(tmember.getId());
            activityListDtos.add(activityListDto);
        }
        return activityListDtos;
    }

    @Override
    public List<SignCorporListDto> getSignCorporIndexList(Short status) {
        String hql = " from TsignupCorporation l where l.status = " + status;
        List<TsignupCorporation> tsignupCorporations = signCorporDao.find(hql);
        List<SignCorporListDto> signCorporListDtos = new ArrayList<>();
        for (TsignupCorporation tsignupCorporation : tsignupCorporations) {
            SignCorporListDto signCorporListDto = new SignCorporListDto();
            BeanUtils.copyProperties(tsignupCorporation, signCorporListDto);
            Tplayer tplayer = playerDao.get(Tplayer.class,
                    tsignupCorporation.getTplayer().getId());
            signCorporListDto.setPlayerId(tplayer.getId());
            signCorporListDto.setPlayerName(tplayer.getName());
            signCorporListDtos.add(signCorporListDto);
        }
        return signCorporListDtos;
    }

    @Override
    public List<AnnouncementListDto> getAnnouncementIndexList(Short status) {
        String hql = " from Tannouncement";
//        String hql = " from Tannouncement l where l.type  " + status;
        List<Tannouncement> tannouncements = announcementDao.find(hql);
        List<AnnouncementListDto> announcementListDtos = new ArrayList<>();
        for (Tannouncement tannouncement : tannouncements) {
            AnnouncementListDto announcementListDto = new AnnouncementListDto();
            BeanUtils.copyProperties(tannouncement, announcementListDto);
            Tmember tmem = memberDao.get(Tmember.class, tannouncement.getPrincipal().getId());
            Tplayer tplayer = playerDao.get(Tplayer.class, tmem.getTplayer().getId());
            Tcorporation corpor = corporationDao.get(Tcorporation.class, tannouncement.getTcorporation().getId());
            announcementListDto.setPrincipalId(tmem.getId());
            announcementListDto.setPrincipalName(tplayer.getName());
            announcementListDto.setCorporarionName(corpor.getName());
            announcementListDto.setCorporarionId(corpor.getId());
            announcementListDtos.add(announcementListDto);
        }
        return announcementListDtos;
    }

    @Override
    public Tcorporation getCloseTimeCorporation() {
        return corporationDao.get("from Tcorporation order by id desc");
    }


    public Tplayer getPlayerByStudentId(String sId) {
        return playerDao.get("from Tplayer p where p.studentId = '"+sId+"'");
    }
    public Long countPlayerByStudentId(String sId) {
        return playerDao.count("select count(*) from Tplayer p where p.studentId = '"+sId+"'");
    }

}
